Search for a Range.md

Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].

  • For example,
  • Given [5, 7, 7, 8, 8, 10] and target value 8,
  • return [3, 4].

题目大意:给定一个升序的数组和一个目标值,返回目标值在数组中的最先出现和最后出现的位置,空间O(1),时间O(N)

题目难度:Medium

/**
 * Created by gzdaijie on 16/5/20
 */
public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result = {-1, -1};
        if(nums == null || nums.length == 0) return result;

        int left = 0, right = nums.length - 1;

        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] < target) left = mid + 1;
            else right = mid;
        }

        if (nums[left] != target) return result;

        result[0] = left;

        while (++left <= nums.length - 1 && nums[left] == target); /* empty */
        result[1] = left - 1;
        return result;
    }
}
gzdaijie            updated 2016-05-20 01:29:09

results matching ""

    No results matching ""